"""
自动备份配置模块

此模块负责自动备份设置的数据库操作，包括设置的保存、加载和表结构管理。
"""

from typing import Dict, Any, Optional, Union
from .models import BackupSettings
from logger_module import log_info, log_warning, log_error


class BackupConfig:
    """
    备份配置管理器
    
    负责管理自动备份设置的持久化存储，通过数据库表进行配置的读写操作。
    提供表结构创建、设置加载和保存等功能。
    """
    
    # 表名常量
    TABLE_NAME = 'auto_backup_settings'
    
    def __init__(self, db_utils=None):
        """
        初始化备份配置管理器
        
        Args:
            db_utils: 数据库工具类实例，用于数据库操作（可选）
        """
        # 如果没有提供db_utils，则自动导入
        if db_utils is None:
            try:
                from db_utils import DatabaseUtils as db_utils
            except ImportError:
                raise ImportError("无法导入db_utils模块，请确保它在Python路径中")
        
        self.db_utils = db_utils
        
    def _ensure_table_exists(self, cursor) -> bool:
        """
        确保备份设置表存在，如果不存在则创建
        
        Args:
            cursor: 数据库游标对象
        
        Returns:
            bool: 表是否存在或创建成功
        """
        try:
            # 检查表是否存在
            cursor.execute(
                """SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?""",
                (self.TABLE_NAME,)
            )
            
            if cursor.fetchone()[0] == 0:
                # 表不存在，创建表
                cursor.execute(f"""
                    CREATE TABLE {self.TABLE_NAME} (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        enabled INTEGER DEFAULT 0,
                        frequency TEXT DEFAULT '每天',
                        backup_time TEXT DEFAULT '00:00',
                        backup_path TEXT
                    )
                """)
                
                return True
            
            return True
            
        except Exception as e:
            log_error(f"创建或检查备份设置表失败: {str(e)}")
            return False
    
    def load_settings(self) -> Dict[str, Any]:
        """
        从数据库加载备份设置
        
        Returns:
            Dict: 备份设置字典，包含enabled, frequency, backup_time, backup_path
        """
        conn = None
        cursor = None
        
        # 默认设置
        default_settings = {
            'enabled': False,
            'frequency': '每天',
            'backup_time': '00:00',
            'backup_path': ''
        }
        
        try:
            # 获取数据库连接，支持不同的方法名
            try:
                if hasattr(self.db_utils, 'get_connection'):
                    conn = self.db_utils.get_connection()
                elif hasattr(self.db_utils, 'create_connection'):
                    conn = self.db_utils.create_connection()
                else:
                    raise AttributeError("数据库工具对象缺少获取连接的方法")
                
                if conn is None:
                    log_warning("无法连接到数据库，返回默认设置")
                    return default_settings.copy()
            except Exception as conn_error:
                log_error(f"获取数据库连接失败: {str(conn_error)}")
                return default_settings.copy()
            
            try:
                cursor = conn.cursor()
                
                # 确保表存在
                if not self._ensure_table_exists(cursor):
                    log_warning("备份设置表不存在或无法创建，返回默认设置")
                    return default_settings.copy()
                
                # 查询设置，使用参数化查询
                cursor.execute(
                    "SELECT enabled, frequency, backup_time, backup_path FROM " + self.TABLE_NAME + " LIMIT 1"
                )
                result = cursor.fetchone()
                
                # 如果有记录，返回设置
                if result:
                    settings = {
                        'enabled': bool(result[0]),
                        'frequency': result[1] if result[1] else '每天',
                        'backup_time': result[2] if result[2] else '00:00',
                        'backup_path': result[3] if result[3] else ''
                    }
                    log_info(f"成功加载备份设置: {settings}")
                    return settings
                else:
                    # 没有记录，插入默认设置
                    log_info("备份设置表为空，插入默认设置")
                    try:
                        cursor.execute(
                            "INSERT INTO " + self.TABLE_NAME + " (enabled, frequency, backup_time, backup_path) VALUES (?, ?, ?, ?)",
                            (0, default_settings['frequency'], default_settings['backup_time'], default_settings['backup_path'])
                        )
                        conn.commit()
                    except Exception as insert_error:
                        log_error(f"插入默认设置失败: {str(insert_error)}")
                    return default_settings.copy()
                    
            except Exception as db_error:
                log_error(f"数据库查询失败: {str(db_error)}")
                return default_settings.copy()
                
        except Exception as e:
            log_error(f"加载备份设置时发生未预期错误: {str(e)}")
            return default_settings.copy()
        finally:
            # 清理资源
            if cursor:
                try:
                    cursor.close()
                except:
                    pass
            if conn:
                try:
                    if hasattr(self.db_utils, 'close_connection'):
                        self.db_utils.close_connection(conn)
                    else:
                        conn.close()
                except Exception as close_error:
                    log_error(f"关闭数据库连接失败: {str(close_error)}")
    
    def save_settings(self, settings: Union[Dict[str, Any], BackupSettings]) -> bool:
        """
        保存备份设置到数据库
        
        Args:
            settings: 包含备份设置的字典或BackupSettings对象
        
        Returns:
            bool: 设置是否保存成功
        """
        conn = None
        cursor = None
        
        try:
            # 处理输入参数，支持字典或BackupSettings对象
            if hasattr(settings, 'to_dict'):
                settings_dict = settings.to_dict()
            else:
                settings_dict = settings
            
            # 获取数据库连接，支持不同的方法名
            try:
                if hasattr(self.db_utils, 'get_connection'):
                    conn = self.db_utils.get_connection()
                elif hasattr(self.db_utils, 'create_connection'):
                    conn = self.db_utils.create_connection()
                else:
                    raise AttributeError("数据库工具对象缺少获取连接的方法")
                
                if conn is None:
                    raise Exception("无法连接到数据库")
            except Exception as conn_error:
                log_error(f"获取数据库连接失败: {str(conn_error)}")
                return False
            
            try:
                cursor = conn.cursor()
                
                # 确保表存在
                if not self._ensure_table_exists(cursor):
                    log_error("无法确保备份设置表存在")
                    return False
                
                # 准备参数
                enabled = 1 if settings_dict.get('enabled', False) else 0
                frequency = settings_dict.get('frequency', '每天')
                backup_time = settings_dict.get('backup_time', '00:00')
                backup_path = settings_dict.get('backup_path', '')
                
                # 使用参数化查询，避免SQL注入
                # 检查表中是否已有记录
                cursor.execute("SELECT id FROM " + self.TABLE_NAME + " LIMIT 1")
                result = cursor.fetchone()
                
                if result:
                    # 更新现有记录
                    cursor.execute(
                        "UPDATE " + self.TABLE_NAME + " SET enabled=?, frequency=?, backup_time=?, backup_path=?",
                        (enabled, frequency, backup_time, backup_path)
                    )
                else:
                    # 插入新记录
                    cursor.execute(
                        "INSERT INTO " + self.TABLE_NAME + " (enabled, frequency, backup_time, backup_path) VALUES (?, ?, ?, ?)",
                        (enabled, frequency, backup_time, backup_path)
                    )
                
                # 提交事务
                conn.commit()
                log_info("备份设置保存成功")
                return True
            except Exception as db_error:
                log_error(f"数据库操作失败: {str(db_error)}")
                # 发生错误时回滚事务
                if conn:
                    try:
                        conn.rollback()
                    except Exception as rollback_error:
                        log_error(f"事务回滚失败: {str(rollback_error)}")
                return False
            
        except Exception as e:
            log_error(f"保存备份设置时发生未预期错误: {str(e)}")
            return False
        finally:
            # 清理资源
            if cursor:
                try:
                    cursor.close()
                except:
                    pass
            if conn:
                try:
                    if hasattr(self.db_utils, 'close_connection'):
                        self.db_utils.close_connection(conn)
                    else:
                        conn.close()
                except Exception as close_error:
                    log_error(f"关闭数据库连接失败: {str(close_error)}")
    
    def reset_settings(self) -> bool:
        """
        重置备份设置为默认值
        
        Returns:
            bool: 重置是否成功
        """
        default_settings = {
            'enabled': False,
            'frequency': '每天',
            'backup_time': '00:00',
            'backup_path': ''
        }
        
        return self.save_settings(default_settings)
    
    def get_settings_table_info(self) -> Optional[Dict[str, Any]]:
        """
        获取备份设置表的信息
        
        Returns:
            Dict: 表信息字典，如果失败则返回None
        """
        conn = None
        cursor = None
        
        try:
            # 获取数据库连接
            conn = self.db_utils.get_connection()
            if conn is None:
                raise Exception("无法连接到数据库")
            
            cursor = conn.cursor()
            
            # 查询表信息
            cursor.execute(
                """SELECT sql FROM sqlite_master WHERE type='table' AND name=?""",
                (self.TABLE_NAME,)
            )
            result = cursor.fetchone()
            
            if result:
                # 查询表中的记录数
                cursor.execute(f"SELECT COUNT(*) FROM {self.TABLE_NAME}")
                record_count = cursor.fetchone()[0]
                
                return {
                    'table_exists': True,
                    'create_sql': result[0],
                    'record_count': record_count
                }
            else:
                return {
                    'table_exists': False,
                    'create_sql': None,
                    'record_count': 0
                }
                
        except Exception as e:
            log_error(f"获取表信息失败: {str(e)}")
            return None
        finally:
            # 清理资源
            if cursor:
                cursor.close()
            if conn:
                self.db_utils.close_connection(conn)